/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import cn.hutool.core.map.MapUtil;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.ExamOrder;
import me.zhengjie.modules.system.domain.WxUser;
import me.zhengjie.modules.system.service.AtmrService;
import me.zhengjie.modules.system.service.ExamOrderService;
import me.zhengjie.modules.system.service.WxUserService;
import me.zhengjie.modules.system.service.dto.AtmrDto;
import me.zhengjie.modules.system.service.dto.ExamOrderDto;
import me.zhengjie.modules.system.service.dto.ExamOrderQueryCriteria;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangyu
 * @website https://el-admin.vip
 * @date 2021-11-25
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "订单管理")
@RequestMapping("/api/examOrder")
public class ExamOrderController {

    private final ExamOrderService examOrderService;

    @Autowired
    private AtmrService atmrService;

    @Autowired
    private WxUserService wxUserService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('examOrder:list')")
    public void download(HttpServletResponse response, ExamOrderQueryCriteria criteria) throws IOException {
        examOrderService.download(examOrderService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询订单")
    @ApiOperation("查询订单")
    @PreAuthorize("@el.check('examOrder:list')")
    public ResponseEntity<Object> query(ExamOrderQueryCriteria criteria, Pageable pageable) {
        String city = criteria.getCity();
        String mobile = criteria.getMobile();
        List<WxUser> wxUsers = null;
        boolean openId = false;
        if (StringUtils.isNotBlank(city) && StringUtils.isNotBlank(mobile)) {
            openId = true;
            wxUsers = wxUserService.findByParam(city, mobile);
        } else if (StringUtils.isNotBlank(city) && StringUtils.isEmpty(mobile)) {
            openId = true;
            wxUsers = wxUserService.findByCity(city);
        } else if (StringUtils.isNotBlank(mobile) && StringUtils.isEmpty(city)) {
            openId = true;
            wxUsers = wxUserService.findByMoblie(mobile);
        }
        //前端传递了姓名或电话号码参数
        if(openId)
        {
            if (null != wxUsers && wxUsers.size() > 0) {
                criteria.setOpenId(wxUsers.get(0).getOpenId());
            }
            else
            {
                criteria.setOpenId("-1");
            }
        }

        Map<String, Object> map = examOrderService.queryAll(criteria, pageable);
        if (MapUtil.isNotEmpty(map) && map.get("content") != null) {
            List<ExamOrderDto> content = examOrderService.queryAll(criteria);
            List<ExamOrderDto> contentList = (List<ExamOrderDto>) map.get("content");
            contentList.parallelStream().forEach(s -> {
                if (null == s.getTeamTestid() || 0 == s.getTeamTestid()) {
                    s.setTeamTestid(0);
                }
                AtmrDto atmrDto = atmrService.findById(Integer.parseInt(s.getAtmrId()));
                if (null != atmrDto) {
                    s.setAtmrName(atmrDto.getAtmrName());
                }
                if (StringUtils.isNotBlank(s.getOpenId())) {
                    WxUser user = wxUserService.findByOpenId(s.getOpenId());
                    s.setWxUser(user);
                    if (null != user) {
                        s.setOpenId(user.getNickname());
                    }
                }
            });
            BigDecimal payTotalAmount = content.parallelStream().map(ExamOrderDto::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            map.put("payTotalAmount", payTotalAmount);
        }
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    @PostMapping
    @Log("新增订单")
    @ApiOperation("新增订单")
    @PreAuthorize("@el.check('examOrder:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody ExamOrder resources) {
        return new ResponseEntity<>(examOrderService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改订单")
    @ApiOperation("修改订单")
    @PreAuthorize("@el.check('examOrder:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody ExamOrder resources) {
        examOrderService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除订单")
    @ApiOperation("删除订单")
    @PreAuthorize("@el.check('examOrder:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        examOrderService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}